<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>UDP / Datagram Sockets | Node.js v8.12.0 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/sh.css">
  <link rel="canonical" href="https://nodejs.org/api/dgram.html">
</head>
<body class="alt apidoc" id="api-section-dgram">
  <div id="content" class="clearfix">
    <div id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Usage &amp; Example</a></li>
</ul>
<div class="line"></div>

<ul>
<li><a class="nav-assert" href="assert.html">Assertion Testing</a></li>
<li><a class="nav-async_hooks" href="async_hooks.html">Async Hooks</a></li>
<li><a class="nav-buffer" href="buffer.html">Buffer</a></li>
<li><a class="nav-addons" href="addons.html">C++ Addons</a></li>
<li><a class="nav-n-api" href="n-api.html">C/C++ Addons - N-API</a></li>
<li><a class="nav-child_process" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster" href="cluster.html">Cluster</a></li>
<li><a class="nav-cli" href="cli.html">Command Line Options</a></li>
<li><a class="nav-console" href="console.html">Console</a></li>
<li><a class="nav-crypto" href="crypto.html">Crypto</a></li>
<li><a class="nav-debugger" href="debugger.html">Debugger</a></li>
<li><a class="nav-deprecations" href="deprecations.html">Deprecated APIs</a></li>
<li><a class="nav-dns" href="dns.html">DNS</a></li>
<li><a class="nav-domain" href="domain.html">Domain</a></li>
<li><a class="nav-esm" href="esm.html">ECMAScript Modules</a></li>
<li><a class="nav-errors" href="errors.html">Errors</a></li>
<li><a class="nav-events" href="events.html">Events</a></li>
<li><a class="nav-fs" href="fs.html">File System</a></li>
<li><a class="nav-globals" href="globals.html">Globals</a></li>
<li><a class="nav-http" href="http.html">HTTP</a></li>
<li><a class="nav-http2" href="http2.html">HTTP/2</a></li>
<li><a class="nav-https" href="https.html">HTTPS</a></li>
<li><a class="nav-inspector" href="inspector.html">Inspector</a></li>
<li><a class="nav-intl" href="intl.html">Internationalization</a></li>
<li><a class="nav-modules" href="modules.html">Modules</a></li>
<li><a class="nav-net" href="net.html">Net</a></li>
<li><a class="nav-os" href="os.html">OS</a></li>
<li><a class="nav-path" href="path.html">Path</a></li>
<li><a class="nav-perf_hooks" href="perf_hooks.html">Performance Hooks</a></li>
<li><a class="nav-process" href="process.html">Process</a></li>
<li><a class="nav-punycode" href="punycode.html">Punycode</a></li>
<li><a class="nav-querystring" href="querystring.html">Query Strings</a></li>
<li><a class="nav-readline" href="readline.html">Readline</a></li>
<li><a class="nav-repl" href="repl.html">REPL</a></li>
<li><a class="nav-stream" href="stream.html">Stream</a></li>
<li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li>
<li><a class="nav-timers" href="timers.html">Timers</a></li>
<li><a class="nav-tls" href="tls.html">TLS/SSL</a></li>
<li><a class="nav-tracing" href="tracing.html">Tracing</a></li>
<li><a class="nav-tty" href="tty.html">TTY</a></li>
<li><a class="nav-dgram active" href="dgram.html">UDP/Datagram</a></li>
<li><a class="nav-url" href="url.html">URL</a></li>
<li><a class="nav-util" href="util.html">Utilities</a></li>
<li><a class="nav-v8" href="v8.html">V8</a></li>
<li><a class="nav-vm" href="vm.html">VM</a></li>
<li><a class="nav-zlib" href="zlib.html">ZLIB</a></li>
</ul>
<div class="line"></div>

<ul>
<li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo &amp; Issue Tracker</a></li>
<li><a class="nav-https-groups-google-com-group-nodejs" href="https://groups.google.com/group/nodejs">Mailing List</a></li>
</ul>

    </div>

    <div id="column1" data-id="dgram" class="interior">
      <header>
        <h1>Node.js v8.12.0 Documentation</h1>
        <div id="gtoc">
          <ul>
            <li>
              <a href="index.html" name="toc">Index</a>
            </li>
            <li>
              <a href="all.html">View on single page</a>
            </li>
            <li>
              <a href="dgram.json">View as JSON</a>
            </li>
            
    <li class="version-picker">
      <a href="#">View another version <span>&#x25bc;</span></a>
      <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v9.x/api/dgram.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/dgram.html">8.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v7.x/api/dgram.html">7.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v6.x/api/dgram.html">6.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v5.x/api/dgram.html">5.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v4.x/api/dgram.html">4.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/dgram.html">0.12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/dgram.html">0.10.x</a></li></ol>
    </li>
  
          </ul>
        </div>
        <hr>
      </header>

      <div id="toc">
        <h2>Table of Contents</h2>
        <ul>
<li><span class="stability_2"><a href="#dgram_udp_datagram_sockets">UDP / Datagram Sockets</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_class_dgram_socket">Class: dgram.Socket</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_event_close">Event: &#39;close&#39;</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_error">Event: &#39;error&#39;</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_listening">Event: &#39;listening&#39;</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_message">Event: &#39;message&#39;</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_addmembership_multicastaddress_multicastinterface">socket.addMembership(multicastAddress[, multicastInterface])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_address">socket.address()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_bind_port_address_callback">socket.bind([port][, address][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_bind_options_callback">socket.bind(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_close_callback">socket.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_dropmembership_multicastaddress_multicastinterface">socket.dropMembership(multicastAddress[, multicastInterface])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_getrecvbuffersize">socket.getRecvBufferSize()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_getsendbuffersize">socket.getSendBufferSize()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_ref">socket.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_send_msg_offset_length_port_address_callback">socket.send(msg, [offset, length,] port [, address] [, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setbroadcast_flag">socket.setBroadcast(flag)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastinterface_multicastinterface">socket.setMulticastInterface(multicastInterface)</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_examples_ipv6_outgoing_multicast_interface">Examples: IPv6 Outgoing Multicast Interface</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_example_ipv4_outgoing_multicast_interface">Example: IPv4 Outgoing Multicast Interface</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_call_results">Call Results</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastloopback_flag">socket.setMulticastLoopback(flag)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastttl_ttl">socket.setMulticastTTL(ttl)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setrecvbuffersize_size">socket.setRecvBufferSize(size)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setsendbuffersize_size">socket.setSendBufferSize(size)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setttl_ttl">socket.setTTL(ttl)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_unref">socket.unref()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_change_to_asynchronous_socket_bind_behavior">Change to asynchronous <code>socket.bind()</code> behavior</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dgram_dgram_module_functions"><code>dgram</code> module functions</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_dgram_createsocket_options_callback">dgram.createSocket(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_dgram_createsocket_type_callback">dgram.createSocket(type[, callback])</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>

      </div>

      <div id="apicontent">
        <h1>UDP / Datagram Sockets<span><a class="mark" href="#dgram_udp_datagram_sockets" id="dgram_udp_datagram_sockets">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!-- name=dgram -->
<p>The <code>dgram</code> module provides an implementation of UDP Datagram sockets.</p>
<pre><code class="lang-js">const dgram = require(&#39;dgram&#39;);
const server = dgram.createSocket(&#39;udp4&#39;);

server.on(&#39;error&#39;, (err) =&gt; {
  console.log(`server error:\n${err.stack}`);
  server.close();
});

server.on(&#39;message&#39;, (msg, rinfo) =&gt; {
  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});

server.on(&#39;listening&#39;, () =&gt; {
  const address = server.address();
  console.log(`server listening ${address.address}:${address.port}`);
});

server.bind(41234);
// server listening 0.0.0.0:41234
</code></pre>
<h2>Class: dgram.Socket<span><a class="mark" href="#dgram_class_dgram_socket" id="dgram_class_dgram_socket">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>The <code>dgram.Socket</code> object is an <a href="events.html"><code>EventEmitter</code></a> that encapsulates the
datagram functionality.</p>
<p>New instances of <code>dgram.Socket</code> are created using <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>.
The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances.</p>
<h3>Event: &#39;close&#39;<span><a class="mark" href="#dgram_event_close" id="dgram_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>The <code>&#39;close&#39;</code> event is emitted after a socket is closed with <a href="#dgram_socket_close_callback"><code>close()</code></a>.
Once triggered, no new <code>&#39;message&#39;</code> events will be emitted on this socket.</p>
<h3>Event: &#39;error&#39;<span><a class="mark" href="#dgram_event_error" id="dgram_event_error">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><ul>
<li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&lt;Error&gt;</a></li>
</ul>
<p>The <code>&#39;error&#39;</code> event is emitted whenever any error occurs. The event handler
function is passed a single Error object.</p>
<h3>Event: &#39;listening&#39;<span><a class="mark" href="#dgram_event_listening" id="dgram_event_listening">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>The <code>&#39;listening&#39;</code> event is emitted whenever a socket begins listening for
datagram messages. This occurs as soon as UDP sockets are created.</p>
<h3>Event: &#39;message&#39;<span><a class="mark" href="#dgram_event_message" id="dgram_event_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>The <code>&#39;message&#39;</code> event is emitted when a new datagram is available on a socket.
The event handler function is passed two arguments: <code>msg</code> and <code>rinfo</code>.</p>
<ul>
<li><code>msg</code> <a href="buffer.html#buffer_class_buffer" class="type">&lt;Buffer&gt;</a> The message.</li>
<li><code>rinfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a> Remote address information.<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a> The sender address.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a> The address family (<code>&#39;IPv4&#39;</code> or <code>&#39;IPv6&#39;</code>).</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> The sender port.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> The message size.</li>
</ul>
</li>
</ul>
<h3>socket.addMembership(multicastAddress[, multicastInterface])<span><a class="mark" href="#dgram_socket_addmembership_multicastaddress_multicastinterface" id="dgram_socket_addmembership_multicastaddress_multicastinterface">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.9</span>
</div><ul>
<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a></li>
</ul>
<p>Tells the kernel to join a multicast group at the given <code>multicastAddress</code> and
<code>multicastInterface</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the
<code>multicastInterface</code> argument is not specified, the operating system will choose
one interface and will add membership to it. To add membership to every
available interface, call <code>addMembership</code> multiple times, once per interface.</p>
<h3>socket.address()<span><a class="mark" href="#dgram_socket_address" id="dgram_socket_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>Returns an object containing the address information for a socket.
For UDP sockets, this object will contain <code>address</code>, <code>family</code> and <code>port</code>
properties.</p>
<h3>socket.bind([port][, address][, callback])<span><a class="mark" href="#dgram_socket_bind_port_address_callback" id="dgram_socket_bind_port_address_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer.</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&lt;Function&gt;</a> with no parameters. Called when binding is complete.</li>
</ul>
<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram
messages on a named <code>port</code> and optional <code>address</code>. If <code>port</code> is not
specified or is <code>0</code>, the operating system will attempt to bind to a
random port. If <code>address</code> is not specified, the operating system will
attempt to listen on all addresses. Once binding is complete, a
<code>&#39;listening&#39;</code> event is emitted and the optional <code>callback</code> function is
called.</p>
<p>Note that specifying both a <code>&#39;listening&#39;</code> event listener and passing a
<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very
useful.</p>
<p>A bound datagram socket keeps the Node.js process running to receive
datagram messages.</p>
<p>If binding fails, an <code>&#39;error&#39;</code> event is generated. In rare case (e.g.
attempting to bind with a closed socket), an <a href="errors.html#errors_class_error"><code>Error</code></a> may be thrown.</p>
<p>Example of a UDP server listening on port 41234:</p>
<pre><code class="lang-js">const dgram = require(&#39;dgram&#39;);
const server = dgram.createSocket(&#39;udp4&#39;);

server.on(&#39;error&#39;, (err) =&gt; {
  console.log(`server error:\n${err.stack}`);
  server.close();
});

server.on(&#39;message&#39;, (msg, rinfo) =&gt; {
  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});

server.on(&#39;listening&#39;, () =&gt; {
  const address = server.address();
  console.log(`server listening ${address.address}:${address.port}`);
});

server.bind(41234);
// server listening 0.0.0.0:41234
</code></pre>
<h3>socket.bind(options[, callback])<span><a class="mark" href="#dgram_socket_bind_options_callback" id="dgram_socket_bind_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a> Required. Supports the following properties:<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;integer&gt;</a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a></li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&lt;boolean&gt;</a></li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&lt;Function&gt;</a></li>
</ul>
<p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram
messages on a named <code>port</code> and optional <code>address</code> that are passed as
properties of an <code>options</code> object passed as the first argument. If
<code>port</code> is not specified or is <code>0</code>, the operating system will attempt
to bind to a random port. If <code>address</code> is not specified, the operating
system will attempt to listen on all addresses. Once binding is
complete, a <code>&#39;listening&#39;</code> event is emitted and the optional <code>callback</code>
function is called.</p>
<p>Note that specifying both a <code>&#39;listening&#39;</code> event listener and passing a
<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very
useful.</p>
<p>The <code>options</code> object may contain an additional <code>exclusive</code> property that is
use when using <code>dgram.Socket</code> objects with the <a href="cluster.html"><code>cluster</code></a> module. When
<code>exclusive</code> is set to <code>false</code> (the default), cluster workers will use the same
underlying socket handle allowing connection handling duties to be shared.
When <code>exclusive</code> is <code>true</code>, however, the handle is not shared and attempted
port sharing results in an error.</p>
<p>A bound datagram socket keeps the Node.js process running to receive
datagram messages.</p>
<p>If binding fails, an <code>&#39;error&#39;</code> event is generated. In rare case (e.g.
attempting to bind with a closed socket), an <a href="errors.html#errors_class_error"><code>Error</code></a> may be thrown.</p>
<p>An example socket listening on an exclusive port is shown below.</p>
<pre><code class="lang-js">socket.bind({
  address: &#39;localhost&#39;,
  port: 8000,
  exclusive: true
});
</code></pre>
<h3>socket.close([callback])<span><a class="mark" href="#dgram_socket_close_callback" id="dgram_socket_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>Close the underlying socket and stop listening for data on it. If a callback is
provided, it is added as a listener for the <a href="#dgram_event_close"><code>&#39;close&#39;</code></a> event.</p>
<h3>socket.dropMembership(multicastAddress[, multicastInterface])<span><a class="mark" href="#dgram_socket_dropmembership_multicastaddress_multicastinterface" id="dgram_socket_dropmembership_multicastaddress_multicastinterface">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.9</span>
</div><ul>
<li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a></li>
</ul>
<p>Instructs the kernel to leave a multicast group at <code>multicastAddress</code> using the
<code>IP_DROP_MEMBERSHIP</code> socket option. This method is automatically called by the
kernel when the socket is closed or the process terminates, so most apps will
never have reason to call this.</p>
<p>If <code>multicastInterface</code> is not specified, the operating system will attempt to
drop membership on all valid interfaces.</p>
<h3>socket.getRecvBufferSize()<span><a class="mark" href="#dgram_socket_getrecvbuffersize" id="dgram_socket_getrecvbuffersize">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> the <code>SO_RCVBUF</code> socket receive buffer size in bytes.</li>
</ul>
<h3>socket.getSendBufferSize()<span><a class="mark" href="#dgram_socket_getsendbuffersize" id="dgram_socket_getsendbuffersize">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> the <code>SO_SNDBUF</code> socket send buffer size in bytes.</li>
</ul>
<h3>socket.ref()<span><a class="mark" href="#dgram_socket_ref" id="dgram_socket_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The <code>socket.unref()</code> method can be used
to exclude the socket from the reference counting that keeps the Node.js
process active. The <code>socket.ref()</code> method adds the socket back to the reference
counting and restores the default behavior.</p>
<p>Calling <code>socket.ref()</code> multiples times will have no additional effect.</p>
<p>The <code>socket.ref()</code> method returns a reference to the socket so calls can be
chained.</p>
<h3>socket.send(msg, [offset, length,] port [, address] [, callback])<span><a class="mark" href="#dgram_socket_send_msg_offset_length_port_address_callback" id="dgram_socket_send_msg_offset_length_port_address_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>msg</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>address</code> parameter is always optional now.</p>
</td></tr>
<tr><td>v6.0.0</td>
<td><p>On success, <code>callback</code> will now be called with an <code>error</code> argument of <code>null</code> rather than <code>0</code>.</p>
</td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>msg</code> parameter can be an array now. Also, the <code>offset</code> and <code>length</code> parameters are optional now.</p>
</td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>msg</code> <a href="buffer.html#buffer_class_buffer" class="type">&lt;Buffer&gt;</a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&lt;Uint8Array&gt;</a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&lt;Array&gt;</a> Message to be sent.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer. Offset in the buffer where the message starts.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer. Number of bytes in the message.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer. Destination port.</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a> Destination hostname or IP address.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&lt;Function&gt;</a> Called when the message has been sent.</li>
</ul>
<p>Broadcasts a datagram on the socket. The destination <code>port</code> and <code>address</code> must
be specified.</p>
<p>The <code>msg</code> argument contains the message to be sent.
Depending on its type, different behavior can apply. If <code>msg</code> is a <code>Buffer</code>
or <code>Uint8Array</code>,
the <code>offset</code> and <code>length</code> specify the offset within the <code>Buffer</code> where the
message begins and the number of bytes in the message, respectively.
If <code>msg</code> is a <code>String</code>, then it is automatically converted to a <code>Buffer</code>
with <code>&#39;utf8&#39;</code> encoding. With messages that
contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with
respect to <a href="buffer.html#buffer_class_method_buffer_bytelength_string_encoding">byte length</a> and not the character position.
If <code>msg</code> is an array, <code>offset</code> and <code>length</code> must not be specified.</p>
<p>The <code>address</code> argument is a string. If the value of <code>address</code> is a host name,
DNS will be used to resolve the address of the host. If <code>address</code> is not
provided or otherwise falsy, <code>&#39;127.0.0.1&#39;</code> (for <code>udp4</code> sockets) or <code>&#39;::1&#39;</code>
(for <code>udp6</code> sockets) will be used by default.</p>
<p>If the socket has not been previously bound with a call to <code>bind</code>, the socket
is assigned a random port number and is bound to the &quot;all interfaces&quot; address
(<code>&#39;0.0.0.0&#39;</code> for <code>udp4</code> sockets, <code>&#39;::0&#39;</code> for <code>udp6</code> sockets.)</p>
<p>An optional <code>callback</code> function may be specified to as a way of reporting
DNS errors or for determining when it is safe to reuse the <code>buf</code> object.
Note that DNS lookups delay the time to send for at least one tick of the
Node.js event loop.</p>
<p>The only way to know for sure that the datagram has been sent is by using a
<code>callback</code>. If an error occurs and a <code>callback</code> is given, the error will be
passed as the first argument to the <code>callback</code>. If a <code>callback</code> is not given,
the error is emitted as an <code>&#39;error&#39;</code> event on the <code>socket</code> object.</p>
<p>Offset and length are optional but both <em>must</em> be set if either are used.
They are supported only when the first argument is a <code>Buffer</code> or <code>Uint8Array</code>.</p>
<p>Example of sending a UDP packet to a random port on <code>localhost</code>;</p>
<pre><code class="lang-js">const dgram = require(&#39;dgram&#39;);
const message = Buffer.from(&#39;Some bytes&#39;);
const client = dgram.createSocket(&#39;udp4&#39;);
client.send(message, 41234, &#39;localhost&#39;, (err) =&gt; {
  client.close();
});
</code></pre>
<p>Example of sending a UDP packet composed of multiple buffers to a random port
on <code>127.0.0.1</code>;</p>
<pre><code class="lang-js">const dgram = require(&#39;dgram&#39;);
const buf1 = Buffer.from(&#39;Some &#39;);
const buf2 = Buffer.from(&#39;bytes&#39;);
const client = dgram.createSocket(&#39;udp4&#39;);
client.send([buf1, buf2], 41234, (err) =&gt; {
  client.close();
});
</code></pre>
<p>Sending multiple buffers might be faster or slower depending on the
application and operating system. It is important to run benchmarks to
determine the optimal strategy on a case-by-case basis. Generally speaking,
however, sending multiple buffers is faster.</p>
<p><strong>A Note about UDP datagram size</strong></p>
<p>The maximum size of an <code>IPv4/v6</code> datagram depends on the <code>MTU</code>
(<em>Maximum Transmission Unit</em>) and on the <code>Payload Length</code> field size.</p>
<ul>
<li><p>The <code>Payload Length</code> field is <code>16 bits</code> wide, which means that a normal
payload exceed 64K octets <em>including</em> the internet header and data
(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);
this is generally true for loopback interfaces, but such long datagram
messages are impractical for most hosts and networks.</p>
</li>
<li><p>The <code>MTU</code> is the largest size a given link layer technology can support for
datagram messages. For any link, <code>IPv4</code> mandates a minimum <code>MTU</code> of <code>68</code>
octets, while the recommended <code>MTU</code> for IPv4 is <code>576</code> (typically recommended
as the <code>MTU</code> for dial-up type applications), whether they arrive whole or in
fragments.</p>
<p>For <code>IPv6</code>, the minimum <code>MTU</code> is <code>1280</code> octets, however, the mandatory minimum
fragment reassembly buffer size is <code>1500</code> octets. The value of <code>68</code> octets is
very small, since most current link layer technologies, like Ethernet, have a
minimum <code>MTU</code> of <code>1500</code>.</p>
</li>
</ul>
<p>It is impossible to know in advance the MTU of each link through which
a packet might travel. Sending a datagram greater than the receiver <code>MTU</code> will
not work because the packet will get silently dropped without informing the
source that the data did not reach its intended recipient.</p>
<h3>socket.setBroadcast(flag)<span><a class="mark" href="#dgram_socket_setbroadcast_flag" id="dgram_socket_setbroadcast_flag">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.9</span>
</div><ul>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&lt;boolean&gt;</a></li>
</ul>
<p>Sets or clears the <code>SO_BROADCAST</code> socket option. When set to <code>true</code>, UDP
packets may be sent to a local interface&#39;s broadcast address.</p>
<h3>socket.setMulticastInterface(multicastInterface)<span><a class="mark" href="#dgram_socket_setmulticastinterface_multicastinterface" id="dgram_socket_setmulticastinterface_multicastinterface">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
</div><ul>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a></li>
</ul>
<p><em>Note: All references to scope in this section are referring to
<a href="https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses">IPv6 Zone Indices</a>, which are defined by <a href="https://tools.ietf.org/html/rfc4007">RFC 4007</a>. In string form, an IP
with a scope index is written as <code>&#39;IP%scope&#39;</code> where scope is an interface name or
interface number.</em></p>
<p>Sets the default outgoing multicast interface of the socket to a chosen
interface or back to system interface selection. The <code>multicastInterface</code> must
be a valid string representation of an IP from the socket&#39;s family.</p>
<p>For IPv4 sockets, this should be the IP configured for the desired physical
interface. All packets sent to multicast on the socket will be sent on the
interface determined by the most recent successful use of this call.</p>
<p>For IPv6 sockets, <code>multicastInterface</code> should include a scope to indicate the
interface as in the examples that follow. In IPv6, individual <code>send</code> calls can
also use explicit scope in addresses, so only packets sent to a multicast
address without specifying an explicit scope are affected by the most recent
successful use of this call.</p>
<h4>Examples: IPv6 Outgoing Multicast Interface<span><a class="mark" href="#dgram_examples_ipv6_outgoing_multicast_interface" id="dgram_examples_ipv6_outgoing_multicast_interface">#</a></span></h4>
<p>On most systems, where scope format uses the interface name:</p>
<pre><code class="lang-js">const socket = dgram.createSocket(&#39;udp6&#39;);

socket.bind(1234, () =&gt; {
  socket.setMulticastInterface(&#39;::%eth1&#39;);
});
</code></pre>
<p>On Windows, where scope format uses an interface number:</p>
<pre><code class="lang-js">const socket = dgram.createSocket(&#39;udp6&#39;);

socket.bind(1234, () =&gt; {
  socket.setMulticastInterface(&#39;::%2&#39;);
});
</code></pre>
<h4>Example: IPv4 Outgoing Multicast Interface<span><a class="mark" href="#dgram_example_ipv4_outgoing_multicast_interface" id="dgram_example_ipv4_outgoing_multicast_interface">#</a></span></h4>
<p>All systems use an IP of the host on the desired physical interface:</p>
<pre><code class="lang-js">const socket = dgram.createSocket(&#39;udp4&#39;);

socket.bind(1234, () =&gt; {
  socket.setMulticastInterface(&#39;10.0.0.2&#39;);
});
</code></pre>
<h4>Call Results<span><a class="mark" href="#dgram_call_results" id="dgram_call_results">#</a></span></h4>
<p>A call on a socket that is not ready to send or no longer open may throw a <em>Not
running</em> <a href="errors.html#errors_class_error"><code>Error</code></a>.</p>
<p>If <code>multicastInterface</code> can not be parsed into an IP then an <em>EINVAL</em>
<a href="errors.html#errors_class_systemerror"><code>System Error</code></a> is thrown.</p>
<p>On IPv4, if <code>multicastInterface</code> is a valid address but does not match any
interface, or if the address does not match the family then
a <a href="errors.html#errors_class_systemerror"><code>System Error</code></a> such as <code>EADDRNOTAVAIL</code> or <code>EPROTONOSUP</code> is thrown.</p>
<p>On IPv6, most errors with specifying or omitting scope will result in the socket
continuing to use (or returning to) the system&#39;s default interface selection.</p>
<p>A socket&#39;s address family&#39;s ANY address (IPv4 <code>&#39;0.0.0.0&#39;</code> or IPv6 <code>&#39;::&#39;</code>) can be
used to return control of the sockets default outgoing interface to the system
for future multicast packets.</p>
<h3>socket.setMulticastLoopback(flag)<span><a class="mark" href="#dgram_socket_setmulticastloopback_flag" id="dgram_socket_setmulticastloopback_flag">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div><ul>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&lt;boolean&gt;</a></li>
</ul>
<p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When set to <code>true</code>,
multicast packets will also be received on the local interface.</p>
<h3>socket.setMulticastTTL(ttl)<span><a class="mark" href="#dgram_socket_setmulticastttl_ttl" id="dgram_socket_setmulticastttl_ttl">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div><ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer.</li>
</ul>
<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. While TTL generally stands for
&quot;Time to Live&quot;, in this context it specifies the number of IP hops that a
packet is allowed to travel through, specifically for multicast traffic. Each
router or gateway that forwards a packet decrements the TTL. If the TTL is
decremented to 0 by a router, it will not be forwarded.</p>
<p>The argument passed to <code>socket.setMulticastTTL()</code> is a number of hops
between 0 and 255. The default on most systems is <code>1</code> but can vary.</p>
<h3>socket.setRecvBufferSize(size)<span><a class="mark" href="#dgram_socket_setrecvbuffersize_size" id="dgram_socket_setrecvbuffersize_size">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div><ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer</li>
</ul>
<p>Sets the <code>SO_RCVBUF</code> socket option. Sets the maximum socket receive buffer
in bytes.</p>
<h3>socket.setSendBufferSize(size)<span><a class="mark" href="#dgram_socket_setsendbuffersize_size" id="dgram_socket_setsendbuffersize_size">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.7.0</span>
</div><ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer</li>
</ul>
<p>Sets the <code>SO_SNDBUF</code> socket option. Sets the maximum socket send buffer
in bytes.</p>
<h3>socket.setTTL(ttl)<span><a class="mark" href="#dgram_socket_setttl_ttl" id="dgram_socket_setttl_ttl">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div><ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> Integer.</li>
</ul>
<p>Sets the <code>IP_TTL</code> socket option. While TTL generally stands for &quot;Time to Live&quot;,
in this context it specifies the number of IP hops that a packet is allowed to
travel through. Each router or gateway that forwards a packet decrements the
TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
Changing TTL values is typically done for network probes or when multicasting.</p>
<p>The argument to <code>socket.setTTL()</code> is a number of hops between 1 and 255.
The default on most systems is 64 but can vary.</p>
<h3>socket.unref()<span><a class="mark" href="#dgram_socket_unref" id="dgram_socket_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The <code>socket.unref()</code> method can be used
to exclude the socket from the reference counting that keeps the Node.js
process active, allowing the process to exit even if the socket is still
listening.</p>
<p>Calling <code>socket.unref()</code> multiple times will have no addition effect.</p>
<p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be
chained.</p>
<h3>Change to asynchronous <code>socket.bind()</code> behavior<span><a class="mark" href="#dgram_change_to_asynchronous_socket_bind_behavior" id="dgram_change_to_asynchronous_socket_bind_behavior">#</a></span></h3>
<p>As of Node.js v0.10, <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a> changed to an asynchronous
execution model. Legacy code that assumes synchronous behavior, as in the
following example:</p>
<pre><code class="lang-js">const s = dgram.createSocket(&#39;udp4&#39;);
s.bind(1234);
s.addMembership(&#39;224.0.0.114&#39;);
</code></pre>
<p>Must be changed to pass a callback function to the <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a>
function:</p>
<pre><code class="lang-js">const s = dgram.createSocket(&#39;udp4&#39;);
s.bind(1234, () =&gt; {
  s.addMembership(&#39;224.0.0.114&#39;);
});
</code></pre>
<h2><code>dgram</code> module functions<span><a class="mark" href="#dgram_dgram_module_functions" id="dgram_dgram_module_functions">#</a></span></h2>
<h3>dgram.createSocket(options[, callback])<span><a class="mark" href="#dgram_dgram_createsocket_options_callback" id="dgram_dgram_createsocket_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.7.0</td>
<td><p>The <code>recvBufferSize</code> and <code>sendBufferSize</code> options are supported now.</p>
</td></tr>
<tr><td>v8.6.0</td>
<td><p>The <code>lookup</code> option is supported.</p>
</td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&lt;Object&gt;</a> Available options are:<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a> The family of socket. Must be either <code>&#39;udp4&#39;</code> or <code>&#39;udp6&#39;</code>.
Required.</li>
<li><code>reuseAddr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&lt;boolean&gt;</a> When <code>true</code> <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will reuse the
address, even if another process has already bound a socket on it.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>recvBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> - Sets the <code>SO_RCVBUF</code> socket value.</li>
<li><code>sendBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&lt;number&gt;</a> - Sets the <code>SO_SNDBUF</code> socket value.</li>
<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&lt;Function&gt;</a> Custom lookup function. <strong>Default:</strong> <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&lt;Function&gt;</a> Attached as a listener for <code>&#39;message&#39;</code> events. Optional.</li>
<li>Returns: <a href="dgram.html#dgram_class_dgram_socket" class="type">&lt;dgram.Socket&gt;</a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object. Once the socket is created, calling
<a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram
messages. When <code>address</code> and <code>port</code> are not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the
method will bind the socket to the &quot;all interfaces&quot; address on a random port
(it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address
and port can be retrieved using <a href="#dgram_socket_address"><code>socket.address().address</code></a> and
<a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p>
<h3>dgram.createSocket(type[, callback])<span><a class="mark" href="#dgram_dgram_createsocket_type_callback" id="dgram_dgram_createsocket_type_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string&gt;</a> - Either &#39;udp4&#39; or &#39;udp6&#39;.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&lt;Function&gt;</a> - Attached as a listener to <code>&#39;message&#39;</code> events.</li>
<li>Returns: <a href="dgram.html#dgram_class_dgram_socket" class="type">&lt;dgram.Socket&gt;</a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object of the specified <code>type</code>. The <code>type</code> argument
can be either <code>udp4</code> or <code>udp6</code>. An optional <code>callback</code> function can be passed
which is added as a listener for <code>&#39;message&#39;</code> events.</p>
<p>Once the socket is created, calling <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the
socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are
not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the method will bind the socket to the &quot;all
interfaces&quot; address on a random port (it does the right thing for both <code>udp4</code>
and <code>udp6</code> sockets). The bound address and port can be retrieved using
<a href="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p>

      </div>
    </div>
  </div>
  <script src="assets/sh_main.js"></script>
  <script src="assets/sh_javascript.min.js"></script>
  <script>highlight(undefined, undefined, 'pre');</script>
  <!-- __TRACKING__ -->
</body>
</html>

